import tkinter
from PIL import Image, ImageTk
# from PIL import ImageGrab
import mysql
# from tkinter import scrolledtext
# from tkinter import ttk
import os
from tkinter import filedialog
import configparser

ini = configparser.ConfigParser()
ini.read("config\\config.ini")


def wxdbwin():
    window2 = tkinter.Toplevel()
    window2.geometry("800x600")
    window2.title("新窗口")
    menubar = tkinter.Menu(window2)
    menu_1 = tkinter.Menu(menubar, tearoff=0)
    menubar.add_cascade(label='账号', menu=menu_1)
    menu_1.add_command(label='登陆')
    menu_1.add_command(label='登出')
    window2["menu"] = menubar
    # window2.resizable(width=False, height=False)
    frametitle = tkinter.Frame(window2)
    label1 = tkinter.Label(frametitle, width=30, text="群列表")
    label1.pack(side="left")
    label2 = tkinter.Label(frametitle, width=20, text="成员列表")
    label2.pack(side="left")
    label3 = tkinter.Label(frametitle, width=30, text="历史内容")
    label3.pack(fill="both")
    frametitle.pack(anchor="w")
    frame1 = tkinter.Frame(window2)
    global listbox1, listbox2, listbox3
    listbox1 = tkinter.Listbox(frame1, width=30, height=25)
    listbox1.pack(padx=2, fill=tkinter.BOTH, expand="yes")
    listbox1.bind("<Double-Button-1>", func=listbox1dbclick)
    rs = mysql.groupslist()
    for r in rs:
        listbox1.insert("end", r)
    frame1.pack(side="left", anchor="n")
    listbox2 = tkinter.Listbox(window2, width=20, height=25)
    listbox2.pack(side="left", anchor="n", padx=2)
    listbox2.bind("<Double-Button-1>", func=listbox2dbclick)
    listbox2.bind("<Button-3>", func=listbox2rightclick)
    listbox3 = tkinter.Listbox(window2, width=30, height=25)
    listbox3.pack(side="left", anchor="n", padx=2)
    listbox3.bind("<Double-1>", func=listbox3dbclick)
    # 右键popmenu
    global menu_pop
    menu_pop = tkinter.Menu(listbox3, tearoff=0)
    menu_pop.add_command(label="整理数据", command=collection)
    global image1
    image1 = tkinter.Label(window2, text="图片预览")
    image1.pack(side="top")
    # window2.mainloop()


def listbox1dbclick(evt):
    listbox2.delete(0, "end")
    global lst_group_name
    lst_group_name = listbox1.get(listbox1.curselection())
    rs = mysql.memberlist(lst_group_name[0])
    for r in rs:
        listbox2.insert("end", r)


def listbox2dbclick(evt):
    listbox3.delete(0, "end")
    lst_member_name = listbox2.get(listbox2.curselection())
    rs = mysql.contentlist(lst_group_name[0], lst_member_name[0])
    global image_path
    for r in rs:
        if r[1]:
            listbox3.insert("end", r[0] + " " + r[1])
        else:
            listbox3.insert("end", r[0] + " " + r[2])
            if r[3] and r[3] != "无路径":
                image_path = os.getcwd() + r[3]


def listbox2rightclick(evt):
    menu_pop.post(evt.x_root, evt.y_root)


def listbox3dbclick(evt):
    # image_path = r"d:/llj.jpg"
    global image_path
    image_path = str(image_path).replace("\\", "/")
    try:
        image_path = Image.open(image_path)
    except:
        image_path = "d:/1.png"
        image_path = Image.open(image_path)
    # imagefile1 = imagefile1.resize((100, 100), Image.ANTIALIAS)
    tk_image1 = ImageTk.PhotoImage(image_path)
    image1.config(image=tk_image1)
    image1.image = tk_image1


def collection():
    selectdata = listbox2.get(listbox2.curselection())[0]
    # print(selectdata)
    result = get_dir_files(file_path='data\\')
    # print(result)
    for r in result:
        print(r)


# def fileListFunc(filePathList):
#     fileList = []
#     for filePath in filePathList:
#         for root, dirs, nondirs in os.walk(filePath):
#             for item in nondirs:
#                 fileList.append(os.path.join(root, item))
#                 print(os.path.join(root, item))
#     return fileList


def get_dir_files(file_path):
    file_lst = []
    selectdata = listbox2.get(listbox2.curselection())[0]
    for file_path, sub_dirs, filenames in os.walk(file_path):
        if file_path.find(selectdata) >= 0:
            if filenames:
                # 如果是文件，则加append到list中
                for filename in filenames:
                    # if filename.find("儿子") >= 0:
                    file_lst.append(os.path.join(file_path, filename))
            for sub_dir in sub_dirs:
                # 如果是目录，则递归调用该函数
                get_dir_files(sub_dir)
    return file_lst


def changefilepath(evt):
    filepath = filedialog.askopenfilename()
    if str(filepath).strip() != "":
        lbl1var.set(filepath)
        print(filepath)
    else:
        print("未更改")


def submitbtnclick():
    wxdbpath = lbl1var.get()
    print(wxdbpath)
    if wxdbpath != "":
        ini.set("path", "wxdbpath", value=wxdbpath)
        ini.write(open('config\\config.ini', "r+"))


def dbpathwin():
    newwin = tkinter.Tk()
    newwin.geometry("400x800")
    newwin.resizable(height=False, width=False)
    newwin.title("数据库路径")
    frame1 = tkinter.Frame(newwin)
    wxdbpath = ini.get("path", "wxdbpath")
    print(wxdbpath)
    global lbl1var
    lbl1var = tkinter.StringVar()
    lbl1var.set(wxdbpath)
    label1 = tkinter.Label(
                           frame1,
                           textvariable=lbl1var,
                           # borderwidth=20,
                           # padx=10,
                           # pady=10,
                           # bg="green",
                           # justify='left',
                           # anchor="w",
                           wraplength=400
                           )
    label1.pack(anchor="e", fill="both")
    label1.bind("<Button-1>", func=changefilepath)
    # button1 = tkinter.Button(frame1, text="设置", width=30, bg="green", fg="white", command=changefilepath)
    # button1.pack()
    frame1.pack(side="top")
    submitbtn = tkinter.Button(newwin, text="保存", command=submitbtnclick)
    submitbtn.pack()
    newwin.mainloop()


if __name__ == "__main__":
    # wxdbwin()
    dbpathwin()


def showwxdbwin():
    wxdbwin()


def showdbpathwin():
    dbpathwin()
    # print(fileListFunc("D:\\"))
    # file_path = 'data\\'
    # filelist = get_dir_files(file_path)
    # for f in filelist:
    #     print(f)
    # print(filelist)
